from django.http import Http404
from django_redis import get_redis_connection
from rest_framework.generics import ListAPIView, RetrieveAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from recruits.models import City, Enterprise, Recruit
from recruits.serializer import CitySerializer, JobSerializer, EnterpriseSerializer, JobDetailSerializer, \
    EnterpriseDetailedSerializer


class CityView(ListAPIView):
    '''获取热门城市'''
    serializer_class = CitySerializer
    queryset = City.objects.all()
    pagination_class = None


class AddEnterpriseCountView(APIView):
    '''增加企业访问次数'''

    def put(self, request, pk):
        try:
            enterprise = Enterprise.objects.get(pk=pk)
            count = enterprise.visits
            enterprise.visits = count + 1
            enterprise.save()
        except Exception:
            raise Http404
        return Response({
            "message": "更新成功",
            "success": True
        })


class RecommendJobView(ListAPIView):
    '''获取推荐职位视图类'''
    serializer_class = JobSerializer
    queryset = Recruit.objects.all()
    pagination_class = None


class LatestJobView(ListAPIView):
    '''最新招聘信息视图类'''
    serializer_class = JobSerializer
    queryset = Recruit.objects.all().order_by('-createtime')
    pagination_class = None


class HotEnterpriseView(ListAPIView):
    '''热门企业视图类'''
    serializer_class = EnterpriseSerializer
    queryset = Enterprise.objects.all().order_by('-visits')
    pagination_class = None


class ColctEnterpriseView(APIView):
    '''收藏公司视图类'''
    permission_classes = [IsAuthenticated]

    def post(self, request, pk):
        redis_conn = get_redis_connection('recruits')
        redis_conn.sadd('act_%s' % request.user.id, pk)
        return Response({'success': True,
                         'message': '收藏成功'})


class CancelCollectView(APIView):
    '''取消收藏'''

    def post(self, request, pk):
        redis_conn = get_redis_connection('recruits')
        redis_conn.srem('act_%s' % request.user.id, pk)
        return Response({'success': True,
                         'message': '取消收藏'})


class SearchRecruitView(APIView):
    '''搜索职务视图类'''

    def post(self, request):
        name = request.data.get('name')
        keyword = request.data.get('keyword')
        if name and keyword:
            recruit = Recruit.objects.filter(city=name, jobname__contains=keyword)

        elif name:
            recruit = Recruit.objects.filter(city=name, jobname='Python')

        elif keyword:
            recruit = Recruit.objects.filter(city='北京', jobname__contains=keyword)

        elif not (name and keyword):
            recruit = Recruit.objects.filter(city='北京', jobname='Python')
        else:
            return Http404

        serializer = JobSerializer(recruit, many=True)
        return Response(serializer.data)


class RecruitsDetailView(RetrieveAPIView):
    '''获取职务详情页面'''
    serializer_class = JobDetailSerializer
    queryset = Recruit.objects.all()


class AddRecruitsView(APIView):
    '''增加企业访问量'''

    def put(self, request, pk):
        try:
            recruit = Recruit.objects.get(pk=pk)
            count = recruit.visits
            recruit.visits = count + 1
            recruit.save()
        except Exception as e:
            raise Http404
        return Response({
            "message": "更新成功",
            "success": True
        })


class CollectRecruitView(APIView):
    permission_classes = [IsAuthenticated]
    '''收藏职位'''

    def post(self, request, pk):
        redis_conn = get_redis_connection('recruits')
        redis_conn.sadd('rec_%s' % request.user.id, pk)
        return Response({'success': True,
                         'message': '收藏成功'})


class CancelCollectedView(APIView):
    '''取消收藏'''

    def post(self, request, pk):
        redis_conn = get_redis_connection('recruits')
        redis_conn.srem('rec_%s' % request.user.id, pk)
        return Response({'success': True,
                         'message': '取消收藏'})


class EnterpriseDetailView(RetrieveAPIView):
    '''企业详情视图类'''
    serializer_class = EnterpriseDetailedSerializer
    queryset = Enterprise.objects.all()
